<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item v-if="hisVersionVal" label="历史版本" prop="hisVersion">
        <el-select :disabled="!isDataMap" @change="changeHisVersion($event)" v-model="queryParams.hisVersion" placeholder="请选择历史版本号" clearable>
          <el-option
            v-for="dict in hisVersions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="表名" prop="tableName">
        <el-input :disabled="!isDataMap"
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="依赖表名" prop="tableNameRely">
        <el-input
          v-model="queryParams.tableNameRely"
          placeholder="请输入依赖表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段名" prop="columnName">
        <el-input
          v-model="queryParams.columnName"
          placeholder="请输入字段名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="依赖字段名" prop="columnNameRely" v-show="showSearchColl">
        <el-input
          v-model="queryParams.columnNameRely"
          placeholder="请输入依赖字段"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源" prop="fileName" v-show="showSearchColl">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="version" v-show="showSearchColl">
        <el-select v-model="queryParams.version" placeholder="请选择版本号" clearable>
          <el-option
            v-for="dict in dict.type.report_version"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" v-show="showSearchColl">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="isDataMap"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reportworld:datamap:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isDataMap"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['reportworld:datamap:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isDataMap"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['reportworld:datamap:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isDataMap"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleCopy"
          v-hasPermi="['reportworld:datamap:copy']"
        >复制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isDataMap"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reportworld:datamap:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="isDataMap"
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['reportworld:datamap:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" :showSearchColl.sync="showSearchColl" :searchColl="searchColl" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="border" max-height="550px" v-loading="loading" :data="datamapList"
              @selection-change="handleSelectionChange" @row-click="rowClick"
              @sort-change="handleSortChange" :row-style="tableRowStyle" ref="datamap">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-hasPermi="['reportworld:datamap:query']"
        label="操作" align="center" width="130" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row,false)"
            v-hasPermi="['reportworld:datamap:query']"
          >详情</el-button>
          <el-button v-if="isDataMap"
                     type="text"
                     icon="el-icon-setting"
                     size="mini"
                     @click="datamapimg(scope.row)"
                     v-hasPermi="['reportworld:datamap:img']"
          >数据地图</el-button>
        </template>
      </el-table-column>
      <el-table-column label="表名"  width="200"align="center" prop="tableName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="字段名" width="180" align="center" prop="columnName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="依赖表名" width="200" align="center" prop="tableNameRely" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="依赖字段名" width="180" align="center" prop="columnNameRely" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="来源" width="180" align="center" prop="fileName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="版本号" width="150" align="center" prop="version" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.report_version" :value="scope.row.version" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" width="150" prop="createBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="编辑时间" align="center" prop="updateTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑人" align="center" width="150" prop="updateBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报表世界依赖信息对话框 -->
    <el-dialog :close-on-click-modal ="false" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="表名" prop="tableName">
              <el-select  style="width: 100%;" filterable clearable v-model="form.tableName"
                         placeholder="请选择原表名" @change="getTableDetailByTableName($event)">
                <el-option
                  v-for="item in tables"
                  :key="item.name"
                  :label="`${item.name}【${item.chineseName}】`"
                  :value="item.name"
                  :disabled="parseInt(item.status) == 2"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="依赖表名" prop="tableNameRely">
              <el-select style="width: 100%;" filterable clearable v-model="form.tableNameRely"
                         placeholder="请选择依赖表" @change="getTableDetailRelyByTableName($event)">
                <el-option
                  v-for="item in tables"
                  :key="item.name"
                  :label="`${item.name}【${item.chineseName}】`"
                  :value="item.name"
                  :disabled="parseInt(item.status) == 2"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段名" prop="columnName">
              <el-select style="width: 100%;" filterable clearable v-model="form.columnName"
                         placeholder="请选择依赖表">
                <el-option
                  v-for="item in tableDetails"
                  :key="item.columnName"
                  :label="`${item.columnName}【${item.columnChineseName}】`"
                  :value="item.columnName"
                  :disabled="parseInt(item.status) == 2"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="依赖字段名" prop="columnNameRely">
              <el-select style="width: 100%;" filterable clearable v-model="form.columnNameRely"
                         placeholder="请选择依赖表">
                <el-option
                  v-for="item in tableDetailsRely"
                  :key="item.columnName"
                  :label="`${item.columnName}【${item.columnChineseName}】`"
                  :value="item.columnName"
                  :disabled="parseInt(item.status) == 2"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源" prop="fileName">
              <el-input clearable v-model="form.fileName" placeholder="请输入来源"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-select :disabled="true" clearable v-model="form.version" placeholder="请选择版本号">
                <el-option
                  v-for="dict in dict.type.report_version"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input maxlength="500" clearable v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="butloading"  v-if="isUpdate">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入对话框 -->
    <el-dialog  :title="upload.title" :close-on-click-modal ="false" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+ '&hisVersion=' + this.queryParams.hisVersion"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--<div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listDatamap, getDatamap, delDatamap, addDatamap, updateDatamap,init,getTableDetailByTableName } from "@/api/reportworld/datamap";
  import { getToken } from "@/utils/auth";
  import { getTableRowStyle } from "@/utils/yss";
  export default {
    props :{
      tableName: {type: String,default: ""},
      hisVersion: { type: String,default: ""}
    },
    name: "datamap",
    dicts: ['sys_common_status','report_version'],
    data() {
      return {
        butloading:false,
        isUpdate: true,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        searchColl:true,
        showSearchColl:false,
        // 总条数
        total: 0,
        // 报表世界依赖信息表格数据
        datamapList: [],
        //表信息
        tables: [],
        tableDetails: [],
        tableDetailsRely: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 历史版本号
        hisVersions:[],
        hisVersion:'',
        isDataMap:true,
        hisVersionVal:true,
        // 导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/reportworld/datamap/readDatamapInfo"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          tableNameRely: null,
          tableName: null,
          columnNameRely: null,
          columnName: null,
          version: null,
          status: null,
          hisVersion:null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          tableName: [
            { required: true, message: "表名不能为空", trigger: "blur" }
          ],
          tableNameRely: [
            { required: true, message: "依赖表名不能为空", trigger: "blur" }
          ],
        },
      };
    },
/*    watch: { //值发生变化重新查询页面数据
      tableName: {
        deep: true,
        handler(val) {
          this.queryParams.tableName=val;
          this.init();
          this.getList();
        }
      }
    },*/
    created() {
      if(this.tableName != undefined && this.tableName ){
        this.queryParams.tableName = this.tableName;
        this.queryParams.hisVersion = this.hisVersion;
        this.isDataMap=false;
        if (!this.queryParams.hisVersion) {
            this.hisVersionVal = false;
        }
        this.init();
        this.getList();
      }else{
        this.init();
        this.getList();
      }
    },
    methods: {
      changeHisVersion(value){
        this.queryParams.hisVersion=value;
        this.init();
        this.getList();
      },
      /** 查询报表世界依赖信息列表 */
      getList() {
        this.loading = true;
        listDatamap(this.queryParams).then(response => {
          this.datamapList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      },
      init(){
        init(this.queryParams).then(response => {
          this.tables=response.tables;
          this.hisVersions=response.hisVersions;
      });
      },
      getTableDetailByTableName(tableName){
        getTableDetailByTableName(tableName,this.queryParams.hisVersion).then(response => {
          this.tableDetails=response.tableDetails;
      });
      },
      getTableDetailRelyByTableName(tableName){
        getTableDetailByTableName(tableName,this.queryParams.hisVersion).then(response => {
          this.tableDetailsRely=response.tableDetails;
      });
      },
      datamapimg(row){
        const tableName= row.tableName;
        // this.$router.push("/reportworld/data-map-img/tableName/" + tableName);
         this.$router.push({ path:"/reportworld/data-map-img/tableName/" + tableName+this.queryParams.hisVersion,
           query: {tableName:tableName,dataCode:'REPORT_DATA_MAP',hisVersion:this.queryParams.hisVersion} });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          tableNameRely: null,
          tableName: null,
          columnNameRely: null,
          columnName: null,
          version: null,
          fileName: null,
          status: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          remark: null,
          hisVersion:null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
        this.getList();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加依赖信息";
        this.isUpdate =true;
        this.form.version = this.dict.type.report_version[0].value;
        this.form.status = parseInt(this.dict.type.sys_common_status[0].value);
        this.tableDetails = null;
        this.tableDetailsRely=null;
        this.form.tableName = this.queryParams.tableName;
        this.getTableDetailByTableName(this.queryParams.tableName);
        if(this.queryParams.hisVersion){
          this.form.version =this.queryParams.hisVersion;
        }
        // 清空下拉框的值
      },
      /** 修改按钮操作 */
      handleUpdate(row,isUpdate) {
        this.reset();
        const id = row.id || this.ids;
        if(isUpdate == false){
          this.queryParams.id=id;
        }else{
          this.queryParams.id=id[0];
        }
        getDatamap(this.queryParams).then(response => {
         this.form = response.data;
         this.getTableDetailByTableName(response.data.tableName);
         this.getTableDetailRelyByTableName(response.data.tableNameRely);
         this.open = true;
         this.title = "修改依赖信息";
         this.isUpdate =true;
          if(isUpdate == false){
            this.title = "依赖信息详情";
            this.isUpdate =false;
          }
      });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.butloading=true;
            this.form.hisVersion =this.queryParams.hisVersion;
            if (this.form.id != null) {
              updateDatamap(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {this.butloading=false});
            } else {
              addDatamap(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {this.butloading=false});
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        const hisVersion= this.queryParams.hisVersion;
        this.$modal.confirm('是否确认删除数据项？').then(function() {
          return delDatamap(ids,hisVersion);
        }).then(() => {
          this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      },
      /** 复制操作 */
      handleCopy(row) {
        this.handleAdd();
        const id = row.id || this.ids;
        this.queryParams.id=id[0];
        getDatamap(this.queryParams).then(response => {
          this.form = response.data;
          this.getTableDetailByTableName(response.data.tableName);
          this.getTableDetailRelyByTableName(response.data.tableNameRely);
          this.form.id = null;
          this.form.version = this.dict.type.report_version[0].value;
          if(this.queryParams.hisVersion){
            this.form.version =this.queryParams.hisVersion;
          }
      });
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "依赖信息导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('reportworld/datamap/importTemplate', {
        }, `依赖信息模板.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 导出按钮操作 */
      handleExport() {
        this.queryParams.ids=JSON.stringify(this.ids);
        this.download('reportworld/datamap/export', {
          ...this.queryParams
      }, `datamap_${new Date().getTime()}.xlsx`)
      },
      tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
      },
      /** 单击选中行数据 */
      rowClick(row) {
        this.$refs.datamap.toggleRowSelection(row);
      }
    }
  };
</script>
